package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2025-06-30
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public Result sendCode(String phone, HttpSession session) {
        //校验手机号的合法性
        if(RegexUtils.isPhoneInvalid(phone)){
            //格式不正确，返回错误信息
            return Result.fail("手机号码格式错误");
        }

        //手机格式校验通过，获取验证码
        String code = RandomUtil.randomNumbers(6);

        //将验证码存储到当前session中
/*        session.setAttribute("code",code);
        session.setAttribute("phone",phone);*/

        //存储到Redis中，设置有效期为120s
        stringRedisTemplate.opsForValue().set(RedisConstants.LOGIN_CODE_KEY+phone,code,RedisConstants.LOGIN_CODE_TTL, TimeUnit.MINUTES);

        //将验证码发送给客户
        log.info("短信验证码发送成功。验证码:{}",code);

        //返回OK
        return Result.ok();
    }


    /**
     * 用用户登录
     * @param loginForm
     * @param session
     * @return
     */
    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //用户信息验证
        String phone = loginForm.getPhone();
        if(phone==null || RegexUtils.isPhoneInvalid(phone)){
            return Result.fail("手机号码格式错误");
        }

        String code = stringRedisTemplate.opsForValue().get(RedisConstants.LOGIN_CODE_KEY + phone);
        if(code==null || !code.equals(loginForm.getCode())){
            return Result.fail("验证码错误");
        }


        //用户存在校验
        User user = query().eq("phone", phone).one();
        if(user==null){
            //用户不存在，创建
            user = createUser(phone);
        }

        //将用户存入当前session，维护登录状态
        //session.setAttribute("user", BeanUtil.copyProperties(user, UserDTO.class));

        //将用户存入Redis中
        //只存储常见信息
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO);

        //Long无法强转成String，使用StringRedisTemplate会将key-value都转为String导致报错
        Long id = (Long) userMap.get("id");
        String idStr = String.valueOf(id);
        userMap.put("id",idStr);

        //设置token
        String token = UUID.randomUUID().toString(true);
        String redisToken = RedisConstants.LOGIN_USER_KEY+token;
        stringRedisTemplate.opsForHash().putAll(redisToken,userMap);
        stringRedisTemplate.expire(redisToken,RedisConstants.LOGIN_USER_TTL,TimeUnit.MINUTES);

        return Result.ok(token);
    }

    @Override
    public Result sign() {
        //获取当前用户
        Long userId = UserHolder.getUser().getId();
        //获取当前日期
        String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern(":yyyy:MM"));
        //拼接key
        String key = "sign:"+userId+date;

        //获取今天的日期属于该月第几天
        int dayOfMouth = LocalDateTime.now().getDayOfMonth() - 1;
        //在redis中插入
        stringRedisTemplate.opsForValue().setBit(key,dayOfMouth,true);

        return Result.ok();
    }

    @Override
    public Result signCount() {
        //获取当前用户
        Long userId = UserHolder.getUser().getId();
        //获取当前日期
        String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern(":yyyy:MM"));
        //拼接key
        String key = "sign:"+userId+date;
        //获取今天的日期属于该月第几天
        int dayOfMouth = LocalDateTime.now().getDayOfMonth();

        List<Long> result = stringRedisTemplate.opsForValue().bitField(
                key,
                BitFieldSubCommands
                        .create()
                        .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMouth))
                        .valueAt(0)
        );

        if(result==null || result.isEmpty()||result.get(0)==null){
            return Result.ok(0);
        }

        Long num = result.get(0);
        int count=0;
        while (true){
            if((num & 1) == 0){
                break;
            }
            count++;
            num = num>>1;
        }

        return Result.ok(count);
    }

    private User createUser(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName(SystemConstants.USER_NICK_NAME_PREFIX+RandomUtil.randomNumbers(10));

        //将用户存入数据库中，MP的save方法会自动将生成的主键赋值给对象
        save(user);

        return user;
    }
}
